今天要來繼續筆記 Solid.js,介紹 batch
跟 createStore
batch
先來看以下一段程式碼:
import { createSignal } from "solid-js"
export default function Hello({name}: {name: string}) {
const [count,setSount] = createSignal<number>(10);
const [age,setAge] = createSignal<number>(0);
const totalValue = ()=>{
console.log('value updated')
return count() + age();
}
const updateValue=()=>{
**batch**(()=>{ //原本沒有使用
setSount(count()+1);
setAge(age()+1);
})
}
return(
<>
<div>Count:{count()}</div>
<div>Age:{age()}</div>
<div>Total:{totalValue()}</div>
<button onClick={()=>updateValue()}></button>
</>
)
}
totalValue 裡面的console.log,在我們每一次按下 button更新 count 和 age (reactive values)時都會印出兩次 'value updated',這時候我們可以使用 batch
,batch 會等被包住的callback 都執行完畢後才會一次印出 console.log('value updated')。
createStore
import { createStore } from "solid-js/store";
export const [personStore, setPersonStore] = createStore({
firstName: 'tai',
lastName:'yeh',
age: 45,
get fullName() {
return `I am ${this.firstName} ${this.lastName} and ${age}-years-old`;
},
})
參考影片: